package com.snailwu.security.KeyGenerator;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * AES 对称加密。加速速度快，适合对接口的参数进行加解密，缺点就是密钥的传输比较麻烦。
 *
 * @author WuQinglong
 * @date 2021/1/19 14:25
 */
public class AESMain {

    public static void main(String[] args) throws Exception {
        // 要加密的数据
        String data = "1234567890";
        // 密钥算法
        String keyAlgorithm = "AES";
        // 加密算法
        String cipherAlgorithm = "AES/ECB/PKCS5PADDING";

        // 获取密钥，Base64解码，封装为 SecretKey
        String key = KeyGeneratorMain.generateKey(keyAlgorithm, null);
        byte[] keyBytes = Base64.getDecoder().decode(key.getBytes());
        SecretKey secretKey = new SecretKeySpec(keyBytes, keyAlgorithm);

        // 加密。对于 AES 来说，默认使用的加密模式是ECB，填充方式为 PKCS5Padding
        Cipher encodeCipher = Cipher.getInstance(cipherAlgorithm);
        encodeCipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptBytes = encodeCipher.doFinal(data.getBytes());
        String encodeStr = Base64.getEncoder().encodeToString(encryptBytes);
        System.out.println("私钥=>公钥：加密：" + encodeStr);

        // 解密。必须与加密使用的算法对应！
        byte[] dataBytes = Base64.getDecoder().decode(encodeStr.getBytes());
        Cipher decodeCipher = Cipher.getInstance(cipherAlgorithm);
        decodeCipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptBytes = decodeCipher.doFinal(dataBytes);
        String decodeStr = new String(decryptBytes);
        System.out.println("私钥=>公钥：解密：" + decodeStr);
    }

}
